package com.member.web.controller.shop;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.member.common.annotation.Anonymous;
import com.member.common.annotation.Log;
import com.member.common.core.controller.BaseController;
import com.member.common.core.domain.AjaxResult;
import com.member.common.core.domain.R;
import com.member.common.core.domain.model.LoginUser;
import com.member.common.core.page.TableDataInfo;
import com.member.common.enums.BusinessType;
import com.member.common.enums.OrderSatusEnum;
import com.member.common.exception.ServiceException;
import com.member.common.utils.DateUtils;
import com.member.common.utils.StringUtils;
import com.member.common.utils.oss.OSSUtils;
import com.member.common.utils.poi.ExcelUtil;
import com.member.shop.domain.*;
import com.member.shop.dto.*;
import com.member.shop.service.ISysBizGoodsSkuService;
import com.member.shop.service.ISysBizOrderGoodsService;
import com.member.shop.service.ISysBizOrderService;
import com.member.shop.service.ISysBizUserService;
import com.member.shop.vo.OrderCodeVo;
import com.member.shop.vo.SysBizOrderExportVo;
import com.member.web.core.config.WxMaConfiguration;
import com.member.web.core.config.WxMaProperties;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 【订单】控制器
 *
 * @author lixinchen
 * @version 1.0
 * @date 2024-01-08
 **/
@Anonymous
@RestController
@RequestMapping("/shop/order")
public class SysBizOrderController extends BaseController {
    @Resource
    private ISysBizOrderService sysBizOrderService;
    @Resource
    private ISysBizOrderGoodsService sysBizOrderGoodsService;
    @Resource
    private ISysBizGoodsSkuService sysBizGoodsSkuService;

    @Autowired
    public RedisTemplate redisTemplate;

    private void setTenantId(SysBizOrder sysBizOrder) {
        Long tenantId = getTenantId();
        if (tenantId != null && tenantId > 0) {
            sysBizOrder.setTenantId(tenantId);
        }
    }

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('shop:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysBizOrder sysBizOrder) {
        startPage();
        setTenantId(sysBizOrder);
        List<SysBizOrder> list = sysBizOrderService.selectSysBizOrderList(sysBizOrder);
        return getDataTable(list);
    }

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('shop:order:list')")
    @GetMapping("/listOrderCode")
    public AjaxResult listOrderCode() {
        List<OrderCodeVo> list = sysBizOrderService.listOrderCode();
        return success(list);
    }

    @PreAuthorize("@ss.hasPermi('shop:order:list')")
    @GetMapping("/listReceiver")
    public AjaxResult listReceiver() {
        List<OrderCodeVo> list = sysBizOrderService.listReceiver();
        if (!CollectionUtils.isEmpty(list)) {
            List<OrderCodeVo> collect = list.stream().distinct().collect(Collectors.toList());
            return success(collect);
        }
        return success(list);
    }

    @PreAuthorize("@ss.hasPermi('shop:order:list')")
    @GetMapping("/listContactNumber")
    public AjaxResult listContactNumber() {
        List<OrderCodeVo> list = sysBizOrderService.listContactNumber();
        if (!CollectionUtils.isEmpty(list)) {
            List<OrderCodeVo> collect = list.stream().distinct().collect(Collectors.toList());
            return success(collect);
        }
        return success(list);
    }

    /**
     * 查询订单列表(统计)
     */
    @PreAuthorize("@ss.hasPermi('shop:order:listOrderCount')")
    @GetMapping("/listOrderCount")
    public TableDataInfo listOrderCount(SysBizOrder sysBizOrder) {
        startPage();
        List<SysBizOrder> list = sysBizOrderService.listOrderCount(sysBizOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('shop:order:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysBizOrder sysBizOrder) {
        setTenantId(sysBizOrder);
        List<SysBizOrderExportVo> list = sysBizOrderService.selectSysBizOrderExportList(sysBizOrder);
        if (!list.isEmpty()) {
            for (SysBizOrderExportVo sysBizOrderExportVo : list) {
                if(sysBizOrderExportVo.getStatus()!=null){
                    OrderSatusEnum byKey = OrderSatusEnum.getByKey(sysBizOrderExportVo.getStatus());
                    if(byKey!=null){
                        sysBizOrderExportVo.setStatusName(byKey.getDesc());
                    }
                }
//                sysBizOrderExportVo.setReceiverAddress(sysBizOrderExportVo.getProvince() + sysBizOrderExportVo.getCity() + sysBizOrderExportVo.getArea() + sysBizOrderExportVo.getReceiverAddress());
                // 判断支付方式
                String payType = "";
                if (sysBizOrderExportVo.getUserCouponId() != null) {
                    payType = "优惠券抵扣";
                }
                if (sysBizOrderExportVo.getPaymentType() != null) {
                    if (sysBizOrderExportVo.getPaymentType() == 0) {
                        if (StringUtils.isNotBlank(payType)) {
                            payType = payType + "+微信支付";
                        } else {
                            payType = "微信支付";
                        }
                    }
                    else if (sysBizOrderExportVo.getPaymentType() == 1) {
                        if (StringUtils.isNotBlank(payType)) {
                            payType = payType + "+支付宝支付";
                        } else {
                            payType = "支付宝支付";
                        }
                    }
                    else if (sysBizOrderExportVo.getPaymentType() == 2) {
                        if (StringUtils.isNotBlank(payType)) {
                            payType = payType + "+余额抵扣";
                        } else {
                            payType = "余额抵扣";
                        }
                    }
                }
                sysBizOrderExportVo.setPaymentTypeName(payType);
            }
        }
        ExcelUtil<SysBizOrderExportVo> util = new ExcelUtil<SysBizOrderExportVo>(SysBizOrderExportVo.class);
        util.exportExcel(response, list, "订单数据");
    }

    /**
     * 批量发货
     */
    @Log(title = "批量发货", businessType = BusinessType.IMPORT)
    @PostMapping("/orderImportData")
    public AjaxResult orderImportData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysBizOrderImport> util = new ExcelUtil<SysBizOrderImport>(SysBizOrderImport.class);
        List<SysBizOrderImport> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = getLoginUser();
        String operName = loginUser.getUsername();
        int message = sysBizOrderService.orderImportData(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    /**
     * 批量发货（模板）
     */
    @PostMapping("/orderTemplate")
    public void rechargeTemplate(HttpServletResponse response) {
        ExcelUtil<SysBizOrderImport> util = new ExcelUtil<>(SysBizOrderImport.class);
        util.importTemplateExcel(response, "批量发货");
    }

    @Resource
    private ISysBizUserService sysBizUserService;

    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('shop:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        SysBizOrder sysBizOrder = sysBizOrderService.selectSysBizOrderById(id);
//        SysBizUser sysBizUser = sysBizUserService.getById(sysBizOrder.getUserId());
//        if (sysBizUser != null) {
//            sysBizOrder.setUserName(sysBizUser.getFullName());
//            sysBizOrder.setPhone(sysBizUser.getUserPhone());
//        }
        sysBizOrder.setAddress(sysBizOrder.getReceiverAddress());
        sysBizOrder.setReceiverAddress(sysBizOrder.getProvince() + sysBizOrder.getCity() + sysBizOrder.getArea() + sysBizOrder.getReceiverAddress());
        SysBizOrderGoods sysBizOrderGoods = new SysBizOrderGoods();
        sysBizOrderGoods.setOrderId(id);
        List<SysBizOrderGoods> sysBizOrderGoodsList = sysBizOrderGoodsService.selectSysBizOrderGoodsList(sysBizOrderGoods);
        if (sysBizOrderGoodsList != null) {
            for (SysBizOrderGoods bizOrderGoods : sysBizOrderGoodsList) {
//                SysBizGoodsSku sysBizGoodsSku = sysBizGoodsSkuService.selectSysBizGoodsSkuByGoodsIdAndKey(bizOrderGoods.getGoodsId(), bizOrderGoods.getSpecsKey());
                bizOrderGoods.setSpecsName(bizOrderGoods.getSpecsKey());
            }
        }
        sysBizOrder.setSysBizOrderGoodsList(sysBizOrderGoodsList);
        // 判断支付方式
        String payType = "";
        if (sysBizOrder.getUserCouponId() != null) {
            payType = "优惠券抵扣";
        }
//        if (sysBizOrder.getBalanceDiscountAmount() != null && sysBizOrder.getBalanceDiscountAmount().compareTo(BigDecimal.ZERO) > 0) {
//            if (StringUtils.isNotBlank(payType)) {
//                payType = payType + "+分账金抵扣";
//            } else {
//                payType = "分账金抵扣";
//            }
//        }
//        if (sysBizOrder.getSurplusAmount() != null && sysBizOrder.getSurplusAmount().compareTo(BigDecimal.ZERO) > 0) {
//            if (StringUtils.isNotBlank(payType)) {
//                payType = payType + "+余额抵扣";
//            } else {
//                payType = "余额抵扣";
//            }
//        }
//        if (sysBizOrder.getFuyouDiscountAmount() != null && sysBizOrder.getFuyouDiscountAmount().compareTo(BigDecimal.ZERO) > 0) {
        if (sysBizOrder.getPaymentType() != null) {
            if (sysBizOrder.getPaymentType() == 0) {
                if (StringUtils.isNotBlank(payType)) {
                    payType = payType + "+微信支付";
                } else {
                    payType = "微信支付";
                }
            }
            else if (sysBizOrder.getPaymentType() == 1) {
                if (StringUtils.isNotBlank(payType)) {
                    payType = payType + "+支付宝支付";
                } else {
                    payType = "支付宝支付";
                }
            }
            else if (sysBizOrder.getPaymentType() == 2) {
                if (StringUtils.isNotBlank(payType)) {
                    payType = payType + "+余额抵扣";
                } else {
                    payType = "余额抵扣";
                }
            }
//            }
        }
        sysBizOrder.setPayType(payType);
        return success(sysBizOrder);
    }

    /**
     * 新增订单
     */
    @PreAuthorize("@ss.hasPermi('shop:order:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysBizOrder sysBizOrder) {
        return toAjax(sysBizOrderService.insertSysBizOrder(sysBizOrder));
    }


    @Resource
    private OSSUtils ossUtils;

    @Resource
    private WxMaProperties wxMaProperties;

//    @Value("${wx.pay.mchId}")
    private String mchId = "1603010466";

    @Anonymous
    @PostMapping("/get_delivery_list")
    public JSONArray get_delivery_list() throws WxErrorException {
        String appid = wxMaProperties.getConfigs().get(0).getAppid();
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        String accessToken = wxService.getAccessToken();
        String phoneUrl = "https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/get_delivery_list?access_token=" + accessToken;
        Map<String, Object> map = new LinkedHashMap<>();
        String res = HttpUtil.post(phoneUrl, JSONObject.toJSONString(map));
        JSONObject jsonObject = JSON.parseObject(res);
        if (!(jsonObject.getIntValue("errcode") == 0)) {
            throw new ServiceException("获取物流配置, 请重试");
        }
        JSONArray deliveryList = jsonObject.getJSONArray("delivery_list");
        return deliveryList;
    }

    @PutMapping("/editReceiver")
    public AjaxResult editReceiver(@RequestBody SysBizOrder sysBizOrder) {
        sysBizOrderService.update(new LambdaUpdateWrapper<SysBizOrder>().eq(SysBizOrder::getId, sysBizOrder.getId()).set(SysBizOrder::getReceiverAddress, sysBizOrder.getAddress()).set(SysBizOrder::getReceiver, sysBizOrder.getReceiver()).set(SysBizOrder::getContactNumber, sysBizOrder.getContactNumber()).set(SysBizOrder::getProvince, sysBizOrder.getProvince()).set(SysBizOrder::getCity, sysBizOrder.getCity()).set(SysBizOrder::getArea, sysBizOrder.getArea()));
        return success();
    }

    @PostMapping("/closeOrder/{id}")
    public AjaxResult closeOrder(@PathVariable Long id) {
        sysBizOrderService.update(new LambdaUpdateWrapper<SysBizOrder>().eq(SysBizOrder::getId, id).set(SysBizOrder::getStatus, 60).set(SysBizOrder::getCancelTime, DateUtils.getNowDate()).set(SysBizOrder::getCancelReason, "平台关闭"));
        return success();
    }


    @RequestMapping("/orderPush/{id}")
    public AjaxResult orderPush(@PathVariable Long id) {
        String s = sysBizOrderService.orderPush(id);
        return success(s);
    }

    /**
     * 发货
     */
    @Anonymous
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysBizOrder sysBizOrder) throws WxErrorException {
        ArrayList<String> strings = new ArrayList<>();
        PrintOrderDto printOrderDto = sysBizOrderService.updateSysBizOrder(sysBizOrder);
        ClassPathResource resource = new ClassPathResource("eletemplet.html");
        String line = "";
        try {
            //读取xml内容
            InputStream in = resource.getInputStream();
            line = StreamUtils.copyToString(in, StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        String data = printOrderDto.getWaybillNumber();
        int width = 245;
        int height = 51;
        String generate = "";
        try {
            generate = ossUtils.generate(data, width, height);
            System.out.println(generate);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        SysBizOrderGoods sysBizOrderGoods = new SysBizOrderGoods();
        sysBizOrderGoods.setOrderId(sysBizOrder.getId());
        List<SysBizOrderGoods> sysBizOrderGoodsList = sysBizOrderGoodsService.selectSysBizOrderGoodsList(sysBizOrderGoods);
        StringBuilder sb = new StringBuilder();
        if (!CollectionUtils.isEmpty(sysBizOrderGoodsList)) {
            for (SysBizOrderGoods bizOrderGoods : sysBizOrderGoodsList) {
                sb.append(bizOrderGoods.getGoodsName()).append(bizOrderGoods.getSpecsKey()).append("*").append(bizOrderGoods.getNumber()).append("、");
            }
            // 删除最后一个顿号
            if (sb.length() > 0) {
                sb.setLength(sb.length() - 1);
            }
        }


        String newStr = line.replace("运货单", printOrderDto.getWaybillNumber()).replace("上海派送部1", printOrderDto.getProvince() + printOrderDto.getCity()).replace("上海派送部2", printOrderDto.getCounty()).replace("收货地址", printOrderDto.getCaddress()).replace("发货人地址", printOrderDto.getSaddress()).replace("发货人电话", printOrderDto.getShipperPhone()).replace("发货人姓名", printOrderDto.getShipperName()).replace("收货人电话", printOrderDto.getConTel()).replace("收货人姓名", printOrderDto.getConName()).replace("品名名称", sb.toString()).replace("备注名称", printOrderDto.getMarkerPen1()).replace("用户订单号名称", printOrderDto.getWaybillNumber()).replace("图片地址", generate).replace("当前时间", DateUtils.getTime());
        strings.add(newStr);
        // 对接微信发货

        SysBizOrder byId = sysBizOrderService.getById(sysBizOrder.getId());
        SysBizUser user = sysBizUserService.getById(byId.getUserId());
        if (byId.getFuyouDiscountAmount().compareTo(BigDecimal.ZERO) > 0 && StringUtils.isNotBlank(user.getOpenId()) && StringUtils.isNotBlank(byId.getTransactionId())) {
            OrderKeyDTO orderKeyDTO = new OrderKeyDTO();
            orderKeyDTO.setOrder_number_type(2);
            orderKeyDTO.setOut_trade_no(byId.getPaymentId());
            orderKeyDTO.setTransaction_id(byId.getTransactionId());
            if (byId.getPaymentType() == 0) {
                orderKeyDTO.setMchid(mchId);
            }
            ShippingDTO shippingDTO = new ShippingDTO();
            shippingDTO.setTracking_no(printOrderDto.getWaybillNumber());
            shippingDTO.setItem_desc(sb.toString());
            shippingDTO.setExpress_company("DBL");
            PayerDTO payerDTO = new PayerDTO();
            if (byId.getPaymentType() == 0) {
                payerDTO.setOpenid(user.getOpenId());
            } else {
                payerDTO.setOpenid(byId.getFyOpenId());
            }
            WxDeliverGoodsDTO vo = new WxDeliverGoodsDTO();
            vo.setOrder_key(orderKeyDTO);
            vo.setShipping_list(Collections.singletonList(shippingDTO));
            vo.setPayer(payerDTO);
            vo.setLogistics_type(1);
            vo.setDelivery_mode(1);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
            vo.setUpload_time(sdf.format(new Date()));
            String appid = wxMaProperties.getConfigs().get(0).getAppid();
            final WxMaService wxService = WxMaConfiguration.getMaService(appid);
            String accessToken = wxService.getAccessToken();
            String url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=" + accessToken;
            String param = JSONObject.toJSONString(vo);
            logger.info("微信小程序-发货信息录入接口入参：{}", param);
            String result = HttpUtil.post(url, param);
            JSONObject jsonObject = JSON.parseObject(result);
            int errcode = jsonObject.getInteger("errcode");
            if (errcode != 0) {
                String errmsg = jsonObject.getString("errmsg");
                String err = String.format("微信小程序-发货信息录入接口异常，code码：%s, msg：%s", errcode, errmsg);
                logger.error(err);
//            throw new ServiceException( "微信小程序-发货信息录入接口异常：" + errmsg);
            }
        }
        return success(strings);
    }


    /**
     * 发货
     */
    @PreAuthorize("@ss.hasPermi('shop:order:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping("/oneShipping/{ids}")
    public AjaxResult oneShipping(@PathVariable Long[] ids) throws WxErrorException {
        ArrayList<String> strings = new ArrayList<>();
        for (Long id : ids) {
            SysBizOrder sysBizOrder = sysBizOrderService.selectSysBizOrderById(id);
            PrintOrderDto printOrderDto = sysBizOrderService.updateSysBizOrder(sysBizOrder);
            ClassPathResource resource = new ClassPathResource("eletemplet.html");
            String line = "";
            try {
                //读取xml内容
                InputStream in = resource.getInputStream();
                line = StreamUtils.copyToString(in, StandardCharsets.UTF_8);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String data = printOrderDto.getWaybillNumber();
            int width = 245;
            int height = 51;
            String generate = "";
            try {
                generate = ossUtils.generate(data, width, height);
                System.out.println(generate);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            SysBizOrderGoods sysBizOrderGoods = new SysBizOrderGoods();
            sysBizOrderGoods.setOrderId(sysBizOrder.getId());
            List<SysBizOrderGoods> sysBizOrderGoodsList = sysBizOrderGoodsService.selectSysBizOrderGoodsList(sysBizOrderGoods);
            StringBuilder sb = new StringBuilder();
            if (!CollectionUtils.isEmpty(sysBizOrderGoodsList)) {
                for (SysBizOrderGoods bizOrderGoods : sysBizOrderGoodsList) {
                    sb.append(bizOrderGoods.getGoodsName()).append(bizOrderGoods.getSpecsKey()).append("*").append(bizOrderGoods.getNumber()).append("、");
                }
                // 删除最后一个顿号
                if (sb.length() > 0) {
                    sb.setLength(sb.length() - 1);
                }
            }
            String newStr = line.replace("运货单", printOrderDto.getWaybillNumber()).replace("上海派送部1", printOrderDto.getProvince() + printOrderDto.getCity()).replace("上海派送部2", printOrderDto.getCounty()).replace("收货地址", printOrderDto.getCaddress()).replace("发货人地址", printOrderDto.getSaddress()).replace("发货人电话", printOrderDto.getShipperPhone()).replace("发货人姓名", printOrderDto.getShipperName()).replace("收货人电话", printOrderDto.getConTel()).replace("收货人姓名", printOrderDto.getConName()).replace("品名名称", sb.toString()).replace("备注名称", printOrderDto.getMarkerPen1()).replace("用户订单号名称", printOrderDto.getWaybillNumber()).replace("图片地址", generate).replace("当前时间", DateUtils.getTime());
            strings.add(newStr);
            // 对接微信发货

            SysBizOrder byId = sysBizOrderService.getById(sysBizOrder.getId());
            SysBizUser user = sysBizUserService.getById(byId.getUserId());
            if (byId.getFuyouDiscountAmount().compareTo(BigDecimal.ZERO) > 0 && StringUtils.isNotBlank(user.getOpenId()) && StringUtils.isNotBlank(byId.getTransactionId())) {
                OrderKeyDTO orderKeyDTO = new OrderKeyDTO();
                orderKeyDTO.setOrder_number_type(2);
                orderKeyDTO.setOut_trade_no(byId.getPaymentId());
                orderKeyDTO.setTransaction_id(byId.getTransactionId());
                if (byId.getPaymentType() == 0) {
                    orderKeyDTO.setMchid(mchId);
                }
                ShippingDTO shippingDTO = new ShippingDTO();
                shippingDTO.setTracking_no(printOrderDto.getWaybillNumber());
                shippingDTO.setItem_desc(sb.toString());
                shippingDTO.setExpress_company("DBL");
                PayerDTO payerDTO = new PayerDTO();
                if (byId.getPaymentType() == 0) {
                    payerDTO.setOpenid(user.getOpenId());
                } else {
                    payerDTO.setOpenid(byId.getFyOpenId());
                }
                WxDeliverGoodsDTO vo = new WxDeliverGoodsDTO();
                vo.setOrder_key(orderKeyDTO);
                vo.setShipping_list(Collections.singletonList(shippingDTO));
                vo.setPayer(payerDTO);
                vo.setLogistics_type(1);
                vo.setDelivery_mode(1);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
                vo.setUpload_time(sdf.format(new Date()));
                String appid = wxMaProperties.getConfigs().get(0).getAppid();
                final WxMaService wxService = WxMaConfiguration.getMaService(appid);
                String accessToken = wxService.getAccessToken();
                String url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=" + accessToken;
                String param = JSONObject.toJSONString(vo);
                logger.info("微信小程序-发货信息录入接口入参：{}", param);
                String result = HttpUtil.post(url, param);
                JSONObject jsonObject = JSON.parseObject(result);
                int errcode = jsonObject.getInteger("errcode");
                if (errcode != 0) {
                    String errmsg = jsonObject.getString("errmsg");
                    String err = String.format("微信小程序-发货信息录入接口异常，code码：%s, msg：%s", errcode, errmsg);
                    logger.error(err);
//            throw new ServiceException( "微信小程序-发货信息录入接口异常：" + errmsg);
                }
            }
        }
        return success(strings);
    }

    /**
     * 删除订单
     */
    @PreAuthorize("@ss.hasPermi('shop:order:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysBizOrderService.deleteSysBizOrderByIds(ids));
    }

    /**
     * 取消订单
     *
     * @param id 订单id
     * @return 结果
     */
    @RequestMapping("/orderCancel/{id}")
    public R<String> cancel(@PathVariable Long id) {
        String lockKey = "order_lock_push";
        try {
            Boolean lockAcquired = redisTemplate.opsForValue().setIfAbsent(lockKey, "locked", 10, TimeUnit.SECONDS); // 设置 10 秒超时锁
            if (Boolean.FALSE.equals(lockAcquired)) {
                return R.fail("订单已经被推送,稍后再试");
            }
            SysBizOrder sysBizOrder = sysBizOrderService.selectSysBizOrderById(id);
            if (sysBizOrder == null) {
                return R.fail("订单不存在");
            }
            //防止定时任务把数据改为20 所以把这个地方改成大于30
            if (sysBizOrder.getStatus() >= 30) {
                return R.fail("订单已发货不能取消");
            }
            // 取消订单
            sysBizOrderService.cancelOrder(sysBizOrder);
            return R.ok();
        } catch (Exception e) {
            return R.fail("取消订单异常");
        }finally {
            redisTemplate.delete(lockKey);
        }
    }
}
